package com.kgcx.system.service;

import com.github.pagehelper.Page;
import com.kgcx.common.bean.RequestData;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.constant.ResultCode;
import com.kgcx.common.eum.CommonDataEeum;
import com.kgcx.common.exception.BusinessException;
import com.kgcx.common.redis.JsonRedisTemplate;
import com.kgcx.common.utils.TokenUtils;
import com.kgcx.dbutils.utils.PageUtils;
import com.kgcx.system.domain.*;
import com.kgcx.system.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

//import com.kgcx.common.utils.MD5Util;

/**
 * @author 吴刚林
 * @date 2017/12/5
 */
@Service
public class UserService {
    @Autowired
    private SysEmployeeMapper sysEmployeeMapper;
    @Resource
    private SysEmployeeRoleMapper sysEmployeeRoleMapper;
    @Resource
    private SysEmployeeCityMapper sysEmployeeCityMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private JsonRedisTemplate jsonRedisTemplate;

    /**
     * 添加系统用户
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnData<?> addSysUser(SysEmployee sysEmployee, String roleIds, String cityCodes) {
        ReturnData<String> returnData = new ReturnData<>();
        SysEmployee objce = sysEmployeeMapper.getSysUserByAccount(sysEmployee.getAccount());
        if (null != objce) {
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg("该账号已存在,请重新输入账号");
            return returnData;
        }
        sysEmployee.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysEmployee.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        // user.setPassword(MD5Util.digest(user.getAccount(), user.getPassword()));
        sysEmployee.setIsDisabled(1);
        sysEmployee.setStatus(1);
        sysEmployee.setIsAdmin(0);
        sysEmployeeMapper.insert(sysEmployee);
        // 添加用户角色
        if (StringUtils.isNotBlank(roleIds)) {
            String roleIdsArray[] = roleIds.split(",");
            for (String roleId : roleIdsArray) {
                SysEmployeeRole sysEmployeeRole = new SysEmployeeRole();
                sysEmployeeRole.setCreateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeRole.setEmployeeId(sysEmployee.getKid());
                sysEmployeeRole.setRoleId(Long.parseLong(roleId));
                sysEmployeeRoleMapper.insert(sysEmployeeRole);
            }
        }
        if (StringUtils.isNotBlank(cityCodes)) {
            String cityCodesArray[] = cityCodes.split(",");
            for (String cityCode : cityCodesArray) {
                SysEmployeeCity sysEmployeeCity = new SysEmployeeCity();
                sysEmployeeCity.setCityCode(cityCode);
                sysEmployeeCity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeCity.setEmployeeId(sysEmployee.getKid());
                sysEmployeeCity.setStatus(CommonDataEeum.DATA_STATE_NORMAL.getCode());
                sysEmployeeCity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeCityMapper.insert(sysEmployeeCity);
            }
        }
        return returnData;
    }

    /**
     * 修改用户信息
     *
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserByKid(SysEmployee sysEmployee, String roleIds, String cityCodes) {
        sysEmployee.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        sysEmployeeMapper.updateUserByKid(sysEmployee);
        // 先删 再添加用户角色
        if (StringUtils.isNotBlank(roleIds)) {
            if ("0".equals(roleIds.trim())) {
                sysEmployeeRoleMapper.deleteByEmployeeId(sysEmployee.getKid());
                return;
            }
            sysEmployeeRoleMapper.deleteByEmployeeId(sysEmployee.getKid());
            String roleIdsArray[] = roleIds.split(",");
            for (String roleId : roleIdsArray) {
                SysEmployeeRole sysEmployeeRole = new SysEmployeeRole();
                sysEmployeeRole.setCreateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeRole.setEmployeeId(sysEmployee.getKid());
                sysEmployeeRole.setRoleId(Long.parseLong(roleId));
                sysEmployeeRoleMapper.insert(sysEmployeeRole);
            }
        }
        if (StringUtils.isNotBlank(cityCodes)) {
            if ("0".equals(cityCodes.trim())) {
                sysEmployeeCityMapper.deleteCityCodeByEmployeeId(sysEmployee.getKid());
                return;
            }
            sysEmployeeCityMapper.deleteCityCodeByEmployeeId(sysEmployee.getKid());
            String cityCodesArray[] = cityCodes.split(",");
            for (String cityCode : cityCodesArray) {
                SysEmployeeCity sysEmployeeCity = new SysEmployeeCity();
                sysEmployeeCity.setCityCode(cityCode);
                sysEmployeeCity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeCity.setEmployeeId(sysEmployee.getKid());
                sysEmployeeCity.setStatus(CommonDataEeum.DATA_STATE_NORMAL.getCode());
                sysEmployeeCity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                sysEmployeeCityMapper.insert(sysEmployeeCity);
            }
        }
    }

    /**
     * 删除系统用户
     *
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        sysEmployeeMapper.deleteByPrimaryKey(userId);//删除用户
        sysEmployeeRoleMapper.deleteByEmployeeId(userId);//删除用户角色
    }

    /**
     * 根据kid获取用户
     *
     * @param rd
     * @return
     */
    public SysEmployee getUserByUserkid(RequestData rd) {
        return sysEmployeeMapper.selectByPrimaryKey(rd.getLong("kid"));
    }

    public SysEmployee getUserByAccount(String account) {
        return sysEmployeeMapper.getSysUserByAccount(account);
    }

    /**
     * 根据用户ID得到该用户是否有url权限
     *
     * @param employeeId
     * @param url
     * @return
     */
    //public Boolean getMenuIdsByemployeeId(Long employeeId,String url) {
    public Boolean roleAuth(RequestData rd) {
        Long employeeId = rd.getLong("employeeId");
        String url = rd.getString("url");
        Boolean is = false;
        SysEmployee sysEmployee = sysEmployeeMapper.selectByPrimaryKey(employeeId);
        if (null != sysEmployee) {
            if (1 == sysEmployee.getIsAdmin()) {
                return true;
            }
        }
        List<Integer> menuIdsList = new ArrayList<>();
        List<Integer> l = new ArrayList<>();
        List<SysEmployeeRole> list = sysEmployeeRoleMapper.selectByEmployeeId(employeeId);
        for (SysEmployeeRole sysEmployeeRole : list) {
            l.add(sysEmployeeRole.getRoleId().intValue());
        }
        if (null == l || l.size() == 0) {
            return is;
        }
        List<SysRoleMenu> menuIds = sysRoleMenuMapper.getMenuByroleIds(l);
        if (null == menuIds || menuIds.size() == 0) {
            return is;
        }
        for (SysRoleMenu sysRoleMenu : menuIds) {
            menuIdsList.add(sysRoleMenu.getMenuId());
        }
        SysMenu sysMenu = sysMenuMapper.selectMenuByUrl(url);
        if (null == sysMenu) {
            return is;
        }
        for (Integer integer : menuIdsList) {
            if (integer == sysMenu.getKid().intValue()) {
                is = true;
            }
        }
        return is;
    }

    /**
     * 根据员工ID获取到城市列表
     *
     * @param rd
     * @return
     */
    public List<SysEmployeeCity> getCityCodeByEmployeeId(RequestData rd) {
        return sysEmployeeCityMapper.getCityCodeByEmployeeId(rd.getLong("employeeId"));
    }

    public List<SysEmployeeCity> getCityCodeByAccount(RequestData rd) {
        return sysEmployeeCityMapper.getCityCodeByAccount(rd.getString("account"));
    }

    public ReturnData<List<SysEmployeeVo>> getSysUserPageList(SysEmployee user, int pageNum, int pageSize) {
        List<SysEmployeeVo> userlist = new ArrayList<>();
        PageUtils.page(pageNum, pageSize);
        Page<SysEmployee> pageInfoList = sysEmployeeMapper.getSysUserPageList(user);
        for (SysEmployee sysEmployee : pageInfoList.getResult()) {
            SysEmployeeVo vo = new SysEmployeeVo();
            List<SysRole> roleList = new ArrayList<>();
            BeanUtils.copyProperties(sysEmployee, vo);
            List<SysEmployeeRole> userRoleList = sysEmployeeRoleMapper.selectByEmployeeId(sysEmployee.getKid());
            for (SysEmployeeRole sysEmployeeRole : userRoleList) {
                SysRole sysRole = sysRoleMapper.selectByPrimaryKey(sysEmployeeRole.getRoleId().intValue());
                if (null != sysRole) {
                    roleList.add(sysRole);
                }
            }
            List<SysEmployeeCity> userCityList = sysEmployeeCityMapper.getCityCodeByEmployeeId(sysEmployee.getKid());
            if (null != userCityList) {
                vo.setCityList(userCityList);
            }
            vo.setRoleList(roleList);
            userlist.add(vo);
        }
        ReturnData returnDa = ReturnData.getResult();
        returnDa.setData(userlist);
        returnDa.setPageNum(pageInfoList.getPageNum());
        returnDa.setTotal((int) pageInfoList.getTotal());
        returnDa.setPages(pageSize);
        return returnDa;
    }

    /**
     * 用户登录
     *
     * @param account
     * @param passWord
     * @return
     */
    public UserDomain sysUserlogin(String account, String passWord) {
        Object o = jsonRedisTemplate.opsForValue().get("SYS_LOGIN_LOCK." + account);
        if (null != o && account.equals(o.toString())) {
            throw new BusinessException(ResultCode.FAIL, "帐号已被锁定两小时");
        }

        if (StringUtils.isBlank(account)) {
            throw new BusinessException(ResultCode.FAIL, "账号不能为空");
        }
        if (StringUtils.isBlank(passWord)) {
            throw new BusinessException(ResultCode.FAIL, "密码不能为空");
        }
        SysEmployee user = sysEmployeeMapper.getSysUserByAccountPass(account, passWord);
        if (null == user) {
            Object sysLoginFail = jsonRedisTemplate.opsForValue().get("SYS_LOGIN_FAIL." + account);
            Integer failNum = 0;
            if (null != sysLoginFail) {
                failNum = (Integer) sysLoginFail;
                if (failNum >= 5) {
                    jsonRedisTemplate.opsForValue().set("SYS_LOGIN_LOCK." + account, account, 1, TimeUnit.HOURS);
                } else {
                    jsonRedisTemplate.opsForValue().set("SYS_LOGIN_FAIL." + account, failNum + 1, 1, TimeUnit.HOURS);
                }
            } else {
                jsonRedisTemplate.opsForValue().set("SYS_LOGIN_FAIL." + account, failNum + 1, 1, TimeUnit.HOURS);
            }
            throw new BusinessException(ResultCode.FAIL, "登录失败，密码或者账号错误");
        }
        UserDomain userDomain = new UserDomain();
        BeanUtils.copyProperties(user, userDomain);
        userDomain.setToken(TokenUtils.getToken(user.getAccount(), TokenUtils.TOKEN_SUBJECT_WEBUSER));
        return userDomain;
    }
}
